package com.woniuxy.dr_mall.controller;


import com.woniuxy.dr_mall.entity.*;
import com.woniuxy.dr_mall.global.ResponseStateCode;
import com.woniuxy.dr_mall.service.*;
import com.woniuxy.dr_mall.utils.Audience;
import com.woniuxy.dr_mall.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张哲轩
 * @since 2021-08-11
 */
@Controller
@CrossOrigin
@Slf4j
@RequestMapping("/dr_mall/drOrders")
public class DrOrdersController {

    @Autowired
    private IDrOrdersService ordersService;
    @Autowired
    private IDrAddressService addressService;
    @Autowired
    private IDrSpecValService specValService;
    @Autowired
    private IDrSpecPriceService specPriceService;
    @Autowired
    private IDrCommentService commentService;

    //叶官鑫 2021-8-19
    @Autowired
    private Audience audience;
    /**
     * 进入到下订单页面
     *
     * @param cartId 从购物车过来会有多个id
     * @param model  存数据用于页面展示
     * @param skuId  从商品详情过来的skuid
     * @return 页面
     */
    @PostMapping("initOrder")
    public String initOrder(int[] cartId, Model model, Integer skuId, HttpSession session) {
        log.debug("cartId:{}", cartId);
        List<DrCart> carts = new ArrayList<>();
        DrSpecPrice sku = null;
        DrUser user = (DrUser) session.getAttribute("user");
        //获取收货地址信息
        List<DrAddress> addresses = addressService.getAllByUserId(user.getId());
        //判断从购物车过来还是点击立即购买过来
        if (cartId != null) {
            //点击购物车进入到的订单页面
            //根据购物车id查询要购买的商品信息
            for (int id : cartId) {
                carts.add(ordersService.getCartsById(id));
            }
            for (DrCart cart : carts) {
                StringBuilder specTotalVal = new StringBuilder("");
                DrSpecPrice specPrice = cart.getSkus();
                //拿购物车里商品的图片信息
                DrPicture picture = cart.getSkus().getProducts().getPicture();
                //从购物车里拿商品
                DrProducts product = cart.getSkus().getProducts();
                //将图片信息加到商品里面.
//            product.setPicture(pictures.get(0));
                specPrice.setProducts(product);
                if (specPrice.getMaterial() != null) {
                    DrSpecVal specVal = specValService.getById(specPrice.getMaterial());
                    specTotalVal.append(specVal.getSpecVal() + " ");
                }
                if (specPrice.getWeight() != null) {
                    DrSpecVal specVal = specValService.getById(specPrice.getWeight());
                    specTotalVal.append(specVal.getSpecVal()).append(" ");
                }
                if (specPrice.getColor() != null) {
                    DrSpecVal specVal = specValService.getById(specPrice.getColor());
                    specTotalVal.append(specVal.getSpecVal()).append(" ");
                }
                if (specPrice.getSeries() != null) {
                    DrSpecVal specVal = specValService.getById(specPrice.getSeries());
                    specTotalVal.append(specVal.getSpecVal()).append(" ");
                }
                if (specPrice.getSize() != null) {
                    DrSpecVal specVal = specValService.getById(specPrice.getSize());
                    specTotalVal.append(specVal.getSpecVal()).append(" ");
                }
                if (specPrice.getType() != null) {
                    DrSpecVal specVal = specValService.getById(specPrice.getType());
                    specTotalVal.append(specVal.getSpecVal()).append(" ");
                }
                specPrice.setSpecVal(specTotalVal.toString());
                cart.setSkus(specPrice);
            }
        } else if (skuId != null) {
            //从立即购买页面过来加订单
            //根据单个skuId查询要购买的商品信息
            StringBuilder specTotalVal = new StringBuilder("");
            sku = specPriceService.getSkuBySkuId(skuId);
            //拿sku里商品的图片信息
            List<DrPicture> pictures = sku.getProducts().getPictures();
            //从sku里拿商品
            DrProducts product = sku.getProducts();
            //将图片信息加到商品里面.
//            product.setPicture(pictures.get(0));
            sku.setProducts(product);
            if (sku.getMaterial() != null) {
                DrSpecVal specVal = specValService.getById(sku.getMaterial());
                specTotalVal.append(specVal.getSpecVal() + " ");
            }
            if (sku.getWeight() != null) {
                DrSpecVal specVal = specValService.getById(sku.getWeight());
                specTotalVal.append(specVal.getSpecVal()).append(" ");
            }
            if (sku.getColor() != null) {
                DrSpecVal specVal = specValService.getById(sku.getColor());
                specTotalVal.append(specVal.getSpecVal()).append(" ");
            }
            if (sku.getSeries() != null) {
                DrSpecVal specVal = specValService.getById(sku.getSeries());
                specTotalVal.append(specVal.getSpecVal()).append(" ");
            }
            if (sku.getSize() != null) {
                DrSpecVal specVal = specValService.getById(sku.getSize());
                specTotalVal.append(specVal.getSpecVal()).append(" ");
            }
            if (sku.getType() != null) {
                DrSpecVal specVal = specValService.getById(sku.getType());
                specTotalVal.append(specVal.getSpecVal()).append(" ");
            }
            sku.setSpecVal(specTotalVal.toString());
        }
        log.debug("sku:{}", sku);
        log.debug("carts:{}", carts);
        log.debug("addresses:{}", addresses);
        model.addAttribute("addresses", addresses);
        model.addAttribute("carts", carts);
        model.addAttribute("cartId", cartId);
        model.addAttribute("skuId", skuId);
        model.addAttribute("sku", sku);
        return "cart_order";
    }

    @PostMapping("addOrder")
    public String addOrder(int[] cartId, int address, Model model, Integer skuId,HttpSession session) {
        log.debug("cartId:{}", cartId);
        log.debug("address:{}", address);
        log.debug("skuId:{}", skuId);
        DrUser user = (DrUser) session.getAttribute("user");
        //增加订单
        //拿到地址
        DrAddress addressMsg = addressService.getById(address);
        //拿到sku
        List<DrCart> carts = new ArrayList<>();
        if (cartId != null) {
            for (int cid : cartId) {
                carts.add(ordersService.getCartsById(cid));
            }
        }
        DrOrders orders = ordersService.add(carts, addressMsg, user.getId(), skuId);
        model.addAttribute("order", orders);
        return "cart_order_success";
    }

    @GetMapping("toPay")
    @ResponseBody
    public MyResponseEntity<String> toPay(int orderId) {
        DrOrders orders = ordersService.getById(orderId);
        orders.setPayTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:dd").format(new Date()));
        orders.setPayType("1");
        ordersService.updateById(orders);
        return MyResponseEntity.SUCCESS;
    }

    @GetMapping("getlist")
    @ResponseBody
    public MyResponseEntity<List<DrOrders>> getList() {
        List<DrOrders> allOrders = ordersService.getAllOrders();
        MyResponseEntity<List<DrOrders>> myResponseEntity = new MyResponseEntity<>();
        myResponseEntity.setCode(ResponseStateCode.SUCCESS);
        myResponseEntity.setMsg("查询成功");
        myResponseEntity.setData(allOrders);
        return myResponseEntity;
    }

    //通过用户id，查询用户的订单信息 叶官鑫 2021-8-16
    @GetMapping("userIdSelectOrders")
    @ResponseBody
    public MyResponseEntity userIdSelectOrders(@RequestHeader("token") String token) {
        int userId = JwtUtil.getId(token, audience.getBase64Secret());
        log.debug("管理员id:{}"+userId);
        System.out.println(ordersService.userIdSelectOrders(userId));
        return new MyResponseEntity(ordersService.userIdSelectOrders(userId));
    }



    @GetMapping("forbid/{id}")
    @ResponseBody
    public MyResponseEntity forbidById(@PathVariable int id){
        ordersService.forbidById(id);
        return MyResponseEntity.SUCCESS;
    }

    //通过用户id和订单id删除订单信息 叶官鑫 2021-8-17
    @GetMapping("deleteOrder")
    @ResponseBody
    public MyResponseEntity idDeleteOrder(@RequestHeader("token") String token,int orderId){
        int userId = JwtUtil.getId(token, audience.getBase64Secret());
        log.debug("管理员id:{}"+userId);
        System.out.println(ordersService.userIdSelectOrders(userId));
        ordersService.idDeleteOrder(userId,orderId);
        return new MyResponseEntity(200,"ok");
    }


    //通过订单id查询订单的信息，以及用户的account 叶官鑫 2021-8-17
     @GetMapping("selectOrder")
     @ResponseBody
     public MyResponseEntity  selectOrderByid(int orderId){
       return new MyResponseEntity( ordersService.selectOrderByid(orderId));
     }

//     //通过订单id查询订单详情 叶官鑫 2021-8-19
//    @GetMapping("selectOrderItem")
//    @ResponseBody
//    public MyResponseEntity selectProductsImformationById(int orderId){
//        return new MyResponseEntity(ordersService.selectProductsImformationById(orderId));
//    }
    //通过订单id查询订单详情 叶官鑫 2021-8-19
    @GetMapping("selectOrderItem")
    @ResponseBody
    public MyResponseEntity selectProductsImformationById(int orderId){
        List<DrOrderItemView> drOrderItemViews = ordersService.selectProductsImformationById(orderId);
        for (DrOrderItemView drOrderItemView : drOrderItemViews) {
            String path = drOrderItemView.getDrPicture().getImage();
            drOrderItemView.getDrPicture().setImage("http://192.168.6.100:8080/"+path);
        }
        return new MyResponseEntity(drOrderItemViews);
    }



    @GetMapping("getCount")
    @ResponseBody
    public MyResponseEntity getCount(){
        //userId暂时固定
        //int userId =
        DrUser drUser = new DrUser();
        drUser.setOrderCount(ordersService.getCountByUserId(1));
        drUser.setCommentCount(commentService.getNotCommentCount(1));
        System.out.println(drUser.toString());
        MyResponseEntity myResponseEntity = new MyResponseEntity();
        myResponseEntity.setData(drUser);
        myResponseEntity.setCode(ResponseStateCode.SUCCESS);

        return myResponseEntity;

    }
}

